/**********************************************************************/
/*
Author: Karan Makkar
Created: Nov 2023
Updated: Aug 2025, by Youssef Assarssah
Description: Balance Tables by Treated in batch (in Admin Data, Lagged
Online Survey Data)
Output: TableA4, TableA6
*/
/**********************************************************************/


/*----------------------------------------------------*/
* Section: Setup
/*----------------------------------------------------*/

* include filepaths 
if "$master_run" !="1" include "./Do/SET_FILEPATHS.do"

clear all
set more off
set matsize 11000

* Log
cap log close
global prefix: display %tdCYND td(`c(current_date)')
log using "$KP_logs/${prefix}_balance_pmo_s22.txt", text replace

* Win Prob Switch
local wp = 0

* Lagged yvar switch
local lag = 0

* SE CLUSTERING (OLS): Individual level
global vce vce(cluster anon_id4)

* PMO Varlist
global pmo_vars "gender urban yrs_school"
global vars_21_1 take_courses ///
        course_hours ///
        employed ///
        self_emp_bus_owner ///
        wage_adj ///
        income_adj ///
        job_search ///
        hh_new_bus ///
        job_satisfy_n ///
        business_ability ///
        switch_industry_1 ///
        tot_cons_adj ///
        ladder_now ///
        any_buy 

global vars_21_2 any_sell ///
        net_ast_buy_w_thous ///
        loan_borrow ///
        loan_get ///
        loan_give ///
        consmooth_move ///
        depressed ///
        accomplish_goals ///
        job_web ///
        ewallet_buy ///
        choose_ewallet ///
        views_gov_help_n ///
        views_allocation_n 

global vars_21 take_courses ///
        course_hours ///
        employed ///
        self_emp_bus_owner ///
        wage_adj ///
        income_adj ///
        job_search ///
        hh_new_bus ///
        job_satisfy_n ///
        business_ability ///
        switch_industry_1 ///
        tot_cons_adj ///
        ladder_now ///
        any_buy ///
        any_sell ///
	    net_ast_buy_w_thous ///
        loan_borrow ///
        loan_get ///
        loan_give ///
        consmooth_move ///
        depressed ///
        accomplish_goals ///
        job_web ///
        ewallet_buy ///
        choose_ewallet ///
        views_gov_help_n ///
        views_allocation_n

* Include makestars program
  include "$KP_do/3 Functions/makestars.do"

/*----------------------------------------------------*/
* Section: Load and Clean PMO
/*----------------------------------------------------*/

* Import 2022 Online Survey 
u anon_id4 control_sample completed consented verified batch startdateDay using "$KP_deid_survey/2022/Clean/072125_survey_21_22_deid_clean_control_merged.dta", clear

* Keep only completers
keep if completed == 1 & consented == 1 & verified == 1
gen online_round = 22

* Append 2021 Online Survey
append using "$KP_deid_survey/2021/Clean/071323_survey_21_deid_clean_merged.dta", keep(anon_id4 completed consented verified batch startdateDay)

* Keep only completers 
keep if completed == 1 & consented == 1 & verified == 1
replace online_round = 21 if mi(online_round)
keep anon_id4 online_round batch startdateDay

*Append SAK, SUS
append using "$KP_deid_sakernas/Clean/sak_aug20_deid_clean_merged.dta", keep(anon_id4 batch sak_round)
append using "$KP_deid_sakernas/Clean/sak_feb21_deid_clean_merged.dta", keep(anon_id4 batch sak_round)
append using "$KP_deid_sakernas/Clean/sak_aug21_deid_clean_merged.dta", keep(anon_id4 batch sak_round)
append using "$KP_deid_susenas/Clean/sus_sep20_deid_clean_merged.dta", keep(anon_id4 batch sus_round)
append using "$KP_deid_susenas/Clean/sus_mar21_deid_clean_merged.dta", keep(anon_id4 batch sus_round)
append using "$KP_deid_susenas/Clean/sus_sep21_deid_clean_merged.dta", keep(anon_id4 batch sus_round)
append using "$KP_deid_susenas/Clean/sus_mar22_deid_clean_merged.dta", keep(anon_id4 batch sus_round)

* Drop non-randomized batch
drop if batch ==1

* Keep only batches/observations used in regressions
gen keep_s22 = online_round == 22 & inrange(batch, 18, 22)
gen keep_s21 = online_round == 21 & inrange(batch, 7, 17)
gen keep_sak = (sak_round == 5 & batch <= 3 | sak_round ==6  & batch <= 11 | sak_round == 7 & batch <= 17)
gen keep_sus = (sus_round == 5 & batch <= 5 | sus_round ==6  & batch <= 11 | sus_round == 7 & batch <= 18 | sus_round == 8 & batch <= 22)

keep if keep_s22 == 1 | keep_s21 == 1 | keep_sak ==1 | keep_sus ==1

* Drop non-randomized batches
drop if inlist(batch, 1, 15)

keep anon_id4 batch sus_round sak_round online_round keep_*

* Merge in employment vars
fmerge m:1 anon_id4 batch using "$KP_deid_admin/Clean/pmo_b1-22_clean_long_deid.dta", assert(2 3) keep(3) nogen keepusing(aaa* education age gender multi_apply_hh urban yrs_school final_test_score win_in_batch strata stratum_win_prob) 

*Education cat
recode education (1/2 = 1) (3 = 2) (4/8 = 3), gen(ed_cat) 

*Age Cat
cap drop age_cat
recode age (0/30 = 1) (31/50 = 2) (51/100 = 3), gen(age_cat) 

*Create common aaa vars
gen unemp_admin = aaa1
replace unemp_admin = aaa20 if mi(unemp_admin)
replace unemp_admin = aaa31 if mi(unemp_admin)

gen employee_admin  = aaa2
replace employee_admin = aaa21 if mi(employee_admin)
replace employee_admin = aaa32 if mi(employee_admin)

gen everwork_admin = aaa3
replace everwork_admin = aaa22 if mi(everwork_admin)
replace everwork_admin = aaa33 if mi(everwork_admin)

gen unemp_covid_admin = aaa4
replace unemp_covid_admin = aaa25 if mi(unemp_covid_admin)
replace unemp_covid_admin = aaa36 if mi(unemp_covid_admin)

gen jobcontract_admin = aaa5
replace jobcontract_admin = aaa24 if mi(jobcontract_admin)
replace jobcontract_admin = aaa35 if mi(jobcontract_admin)

gen selfemp_admin = aaa6
replace selfemp_admin = aaa23 if mi(selfemp_admin)
replace selfemp_admin = aaa34 if mi(selfemp_admin)

gen covidimpact_admin = aaa7
replace covidimpact_admin = aaa26 if mi(covidimpact)
replace covidimpact_admin = aaa37 if mi(covidimpact)

*Replacing missings acc to skip logic
replace unemp_admin = 0 if mi(unemp_admin) & (employee_admin ==1 | selfemp_admin ==1) // is not unemployed if employee
replace employee_admin = 0 if mi(employee_admin) & unemp_admin ==1 // is not employee if unemployed
replace everwork_admin = 1 if mi(everwork_admin) & (unemp_admin ==0| employee_admin ==1 | selfemp_admin ==1 | covidimpact_admin ==1| jobcontract_admin ==1)  // has worked before employee or self emp or impacted or job contract. Also ever worked if unemp = 0 (assuming unemp = 0 if not people out of labor force)
replace unemp_covid_admin = 0 if mi(unemp_covid_admin) & (employee_admin == 1 | unemp_admin == 0 | selfemp_admin ==1 | everwork_admin ==0 ) // not covid unemployed if not unemployed
replace jobcontract_admin = 0 if mi(jobcontract_admin) & (selfemp_admin == 1 | everwork_admin ==0 | employee_admin == 0) //if self employed, or not unemp due to covid they don't have work contract
replace selfemp_admin = 0 if mi(selfemp_admin) & (unemp_admin == 1 | employee_admin == 1)  // not an entrepreneur if unemployed or an employee
replace covidimpact_admin = 0 if mi(covidimpact_admin) & selfemp_admin ==0 // No covid business impact if not self emp

foreach var of varlist unemp_admin employee_admin everwork_admin unemp_covid_admin jobcontract_admin selfemp_admin covidimpact_admin {
replace `var' = . if `var' ==3
}

* Create lagged yvar
foreach v of varlist $pmo_vars {
    bysort anon_id4 (batch): gen `v'_lag = `v'[_n-1] if _n !=1
}

* Labelling
label var gender "Male"
label var urban "Urban"
label var yrs_school "Years of School"
 
/*----------------------------------------------------*/
* Section: Make PMO Table
/*----------------------------------------------------*/

foreach x in "sak" "sus" "s22" {
    
    * Panel text
    if "`x'" == "sak" {
        local paneltext = "\\ \multicolumn{4}{l}{\textit{Panel A: Workforce Survey Respondents}} \\\\[-2.5ex]"
        local batchtext = "2-14, 16-17"
        local wave "sak_round"
    }
    if "`x'" == "sus" {
         local paneltext = "\\ \multicolumn{4}{l}{\textit{Panel B: Welfare Survey Respondents}} \\\\[-2.5ex]"
         local batchtext = "2-14, 16-22"
         local wave "sus_round"
    }
    if "`x'" == "s22" {
        local paneltext = "\\ \multicolumn{4}{l}{\textit{Panel C: Online Survey 2022 Respondents}} \\\\[-2.5ex]"
        local batchtext = "18-22"
    }
    * STORE VARIABLE LABELS IN LOCAL MACROS
    foreach v of varlist $pmo_vars {
        local `v'_label: var label `v'
    }

    * Sum Table 
    local i=-1
    local j=0

    * initialize elements for list
    local format = "%12.3fc"
    global outcome_names = `"   "'
    tokenize `"$pmo_vars"'
    local num : word count $pmo_vars
    forval z = 1/`num' {
        local outcome`z' = "``z''"
    }
            
    foreach var in $pmo_vars {

        local i=`i'+2
        local j=`j'+2
        local f = `j'+2

        di "`var'"

        local r`i'_c0: variable label `var'
        
        di "`r`i'_c0'"

        su `var'

        if (`r(mean)'!=0) & (`r(N)'!=0) {

        *Mean  - all
        ** Report applied
        summ `var' if win_in_batch==1 & keep_`x' ==1
        local r`i'_c1 = string(r(mean),"%4.3fc")
        local r`j'_c1 = "(" + string(r(sd),"%4.3fc") + ")"

        ** DO NOT Report applied
        summ `var' if win_in_batch==0 & keep_`x' ==1
        local r`i'_c2 = string(r(mean),"%4.3fc")
        local r`j'_c2 = "(" + string(r(sd),"%4.3fc") + ")"

        ** regressing to get t-stats

        if "`x'" != "s22" reghdfe `var' win_in_batch if keep_`x' ==1, absorb(c.stratum_win_prob#batch#`wave' `wave'#batch) $vce
        else reghdfe `var' win_in_batch if keep_`x' ==1, absorb(c.stratum_win_prob#batch batch) $vce

            local beta =  r(table)[1,1]
            local pval = r(table)[4,1]
            local se = r(table)[2,1]
            local tstats = r(table)[3,1]
            
            local r`j'_c3 = "(" + string(`se',"%4.3fc") + ")"
            local r`f'_c3 = string(e(N), "%9.0fc") 

            makestars, pointest(`beta') pval(`pval') bdec(3)
            di "`r(coeff)'"
            local r`i'_c3 = r(coeff)
        }
    }

    * final row with observations
        local f=`j'+2
        local f_1=`j'+3

    * to know the number of variables displayed in total in the balance table
    di "`i' : number of variables "

    * Get observation counts
    summ final_test_score if win_in_batch==1 & keep_`x' ==1
        local r`f'_c1 = string(r(N), "%9.0fc")
        di "`r`f'_c1'"
        
    summ final_test_score if win_in_batch==0 & keep_`x' ==1
        local r`f'_c2 = string(r(N), "%9.0fc")    
        di "`r`f'_c2'"    
	
    * Add joint F-test for covariate balance
    if "`x'" != "s22" { 
    	reghdfe win_in_batch $pmo_vars if keep_`x' ==1, absorb(c.stratum_win_prob#batch#`wave' `wave'#batch) $vce 
	}
    else { 
    	reghdfe win_in_batch $pmo_vars if keep_`x' ==1, absorb(c.stratum_win_prob#batch batch) $vce 
	}
    
    * Get F-stata and p-values
    test $pmo_vars
    scalar fstat = r(F)
    scalar fpval = r(p)
    
    local fstr = string(fstat, "%4.2f")
    local fstars = cond(fpval < 0.01, "***", cond(fpval < 0.05, "**", cond(fpval < 0.10, "*", "")))
dis "`fstr'"
    // ** write table header

    local tex_file = "$KP_output/tables/descriptive/tex/TableA4.tex"

    if "`x'" == "sak" {
        tempname myfile
        #delimit ;
        file open `myfile' using "`tex_file'", write replace;
        file write `myfile'
        _n "\hline \hline"
        _n " Variable & Treatment & Control & Difference \\"
        _n " & (1) & (2) & (3) \\"
        _n " \hline"
        _n "`paneltext'"

        ;
        file close `myfile' ;
        #delimit cr
    }

    else {
        tempname myfile
        #delimit ;
        file open `myfile' using "`tex_file'", write append;
        file write `myfile'
        _n "`paneltext'"
        ;
        file close `myfile' ;
        #delimit cr
    }

    ** write table body

    di "`=`num'*2'"

    forval row = 1 / `=`num'*2' {
        tempname myfile
        
        #delimit ;
        file open `myfile' using "`tex_file'", write append;
        file write `myfile'
        _n "`r`row'_c0' & `r`row'_c1' & `r`row'_c2' & `r`row'_c3' \\ " ;
        file close `myfile';
        #delimit cr
    }

    ** write table footer
    tempname myfile
    #delimit ;
    file open `myfile' using "`tex_file'", write append;
    file write `myfile'
    _n "\\ F-stat (joint test) &  &  & `fstr'`fstars' \\"
    _n "Observations & `r`f'_c1' & `r`f'_c2' & `r`f'_c3' \\"
    _n "Batches & `batchtext' & `batchtext' & `batchtext' \\"
    _n "\hline"
    ;
    file close `myfile';
    #delimit cr

}

keep if keep_s22 ==1
keep *_admin final_test_score anon_id4 batch
tempfile s22
sa `s22', replace
/*----------------------------------------------------*/
* Section: Load and Clean Online Survey Data
/*----------------------------------------------------*/

* Save Batch Announcement Date Tempfile
import excel "$KP_deid_admin/Raw/00 Kartu Prakerja Batch Schedule.xlsx", sheet("Batch opening schedule") firstrow clear

replace batch = subinstr(batch, "*", "", .)
destring batch, replace

keep batch announcement

drop if mi(batch)

format announcement %td

tempfile batch_dates
sa `batch_dates', replace

* Load Survey 22 Data
u anon_id4 batch win_in_batch gender urban age education yrs_school multi_apply_hh strata stratum_win_prob completed consented verified  batch using "$KP_deid_survey/2022/Clean/072125_survey_21_22_deid_clean_control_merged.dta", clear

keep if completed == 1 & consented == 1 & verified == 1

* Drop non-randomized batches
drop if inlist(batch, 1, 15)

* Merge in batch announcement dates
fmerge m:1 batch using `batch_dates', assert(2 3) keep(3) keepusing(announcement) nogen

* Merge in 2021 Data
global exclude net_ast_buy_w_thous
local vl_21 : list global(vars_21) - global(exclude) // net_ast will be generated below
dis "`vl_21'"
fmerge m:1 anon_id4 using "$KP_deid_survey/2021/Clean/071323_survey_21_deid_clean.dta", ///
       nogen assert(2 3) keep(3) keepusing(`vl_21' bike_* devices_* gold_* livestock_* startdateDay)

* Merge in Admin Vars
fmerge 1:1 anon_id4 batch using `s22', nogen assert(1 3) keep(3)

* Keep only batches announced after the survey date
gen batch_after_s21 = startdateDay < announcement

*Education cat
recode education (1/2 = 1) (3 = 2) (4/8 = 3), gen(ed_cat) 

*Age Cat
cap drop age_cat
recode age (0/30 = 1) (31/50 = 2) (51/100 = 3), gen(age_cat) 

*Winsorize hours course
winsor2 course_hours, replace cut(0 99)

// Generate total value of assets purchased/sold (KA02, KA06, KA10, KA14)
* Handl NA, if indv didn't buy/sell (0) and it's NA if they buy and still missing 

preserve 

* Calculate at the individual level 
duplicates drop anon_id4 bike_* devices_* gold_* livestock_*, force
distinct anon_id4 // 3945
  
* Replace asset values with 0 if the indiv didn't buy/sell 
local asset_types bike devices gold livestock

foreach type in `asset_types'  {
    foreach action in buy sell {
        local var "`type'_`action'"
        replace `var'_val = 0 if `var' == 0
	
	local `action'_val_vars ``action'_val_vars' `type'_`action'_val
	}
}

* Generate the sum variables
foreach action in buy sell {
	egen tot_ast_`action' = rowtotal(``action'_val_vars'), mis
}

rename tot_ast_sell tot_ast_sold 
* Winsorize total asset vars at 99.5th percentile
winsor2 tot_ast_buy* tot_ast_sold*, cuts(0 99.5) suffix(_w)

* Generate Net asset puchases
foreach suff in "" "_w" {
	gen net_ast_buy`suff'  = tot_ast_buy`suff'  - tot_ast_sold`suff'
	gen net_ast_sold`suff' = tot_ast_sold`suff' - tot_ast_buy`suff' 
}

* Generate thousand scaled vars 
local thous_vars tot_ast_buy tot_ast_sold tot_ast_buy_w tot_ast_sold_w /// 
               net_ast_buy net_ast_buy_w  

foreach var of local thous_vars {
	cap drop `var'_thous
	gen `var'_thous = `var'/1000
	local vars_thous `vars_mil' `var'_thous
	
	* Label new variable 
		local label : variable label `var'
		dis "`label'"
		label variable `var'_thous "`label' (thousands IDR)"
}

tempfile asset_data
save `asset_data'
restore 

* Merge back with person-batch level data 
merge m:1 anon_id4 using `asset_data', gen(merge_asset)


* Label 
label var gender "\shortstack[l]{\textit{Panel A: Admin Data} \\ Male}"
label var urban "Urban"
label var yrs_school "Years of School"
label var take_courses "\shortstack[l]{\textit{Panel A: Training} \\ Took a course}"
label var course_hours "Hours of Training"
label var employed "\shortstack[l]{\textit{Panel B: Employment} \\ Employed}"
label var self_emp_bus_owner "Self Employed/Business Owner"
label var wage_adj "Hourly Wage"
label var income_adj "Total Earnings"
label var job_search "Searching for Job (Last Week)"
label var hh_new_bus "HH Prepping New Business"
label var job_satisfy_n "Job Satisfaction"
label var business_ability "Business Ability Confidence"
label var switch_industry_1  "Changed Industry from Feb '20"
label var tot_cons_adj "\shortstack[l]{\textit{Panel C: Cons. \& Cons. Smoothing}\\Total Consumption}"
label var ladder_now "Life Satisfaction"
label var any_buy "Buy any asset"
label var any_sell "Sell any asset"
label var loan_borrow "Taken additional loans"
label var loan_get "Received gifts"
label var loan_give "Gave gifts"
label var consmooth_move "Moved"
label var depressed "\shortstack[l]{\textit{Panel D: Psychometric} \\ Feeling Depressed}"
label var accomplish_goals "Able to Accomplish Goals"
label var job_web "\shortstack[l]{\textit{Panel E: Digital Skills, Comfort}\\Use Internet on Job}"
label var ewallet_buy "Made any E-Wallet purchase"
label var choose_ewallet "Choose E-Wallet over Phone Credit"
label var views_gov_help_n "\shortstack[l]{\textit{Panel F: Govt Program Beliefs}\\Govt Responsible for Helping the Poor}"
label var views_allocation_n "Assistance Should Prioritise the Poor"
label var net_ast_buy_w_thous "Net Asset Purchases"

/*----------------------------------------------------*/
* Section: Make Survey Table
/*----------------------------------------------------*/

forvalues k = 1/2 {
    
    global varlist = "${vars_21_`k'}"

    * STORE VARIABLE LABELS IN LOCAL MACROS
    foreach v of varlist $varlist {
        local `v'_label: var label `v'
    }
    
            
    * Sum Table 
    local i=-1
    local j=0

    * initialize elements for list
    local format = "%12.3fc"
    global outcome_names = `"   "'
    tokenize `"$varlist"'
    local num : word count $varlist
    forval z = 1/`num' {
        local outcome`z' = "``z''"
    }

    foreach var of varlist $varlist {

        local i=`i'+2
        local j=`j'+2
        local f = `j'+2

        di "`var'"

        if "`var'" != "views_gov_help_n" local r`i'_c0: variable label `var'
        else local r`i'_c0 "\shortstack[l]{\textit{Panel F: Govt Program Beliefs}\\Govt Responsible for Helping the Poor}"
        
        di "`r`i'_c0'"

        su `var'
        if (`r(mean)'!=0) & (`r(N)'!=0) {

        *Mean  - all
        ** Report applied
        summ `var' if win_in_batch==1 & batch_after_s21 ==1
        local r`i'_c1 = string(r(mean), "%9.3fc")
        local r`j'_c1 = "(" + string(r(sd),"%4.3fc") + ")"

        ** DO NOT Report applied
        summ `var' if win_in_batch==0 & batch_after_s21 ==1
        local r`i'_c2 = string(r(mean),"%4.3fc")
        local r`j'_c2 = "(" + string(r(sd),"%4.3fc") + ")"

        ** regressing to get t-stats

        reghdfe `var' win_in_batch if inrange(batch, 7, 22) & batch_after_s21 ==1, absorb(c.stratum_win_prob#batch batch) $vce

            local beta =  r(table)[1,1]
            local pval = r(table)[4,1]
            local se = r(table)[2,1]
            local tstats = r(table)[3,1]

            local r`j'_c3 = "(" + string(`se',"%4.3fc") + ")"
            local r`f'_c3 = string(e(N), "%9.0fc") 
            
            makestars, pointest(`beta') pval(`pval') bdec(3)
            di "`r(coeff)'"
            local r`i'_c3 = r(coeff) 
        }
    }

    * final row with observations
        local f=`j'+2
        local f_1=`j'+3

    * to know the number of variables displayed in total in the balance table
    di "`i' : number of variables "

    * Get observation counts
    summ anon_id4 if win_in_batch==1 & batch_after_s21 ==1
        local r`f'_c1 = string(r(N), "%9.0fc")
        di "`r`f'_c1'"
        
    summ anon_id4 if win_in_batch==0 & batch_after_s21 ==1
        local r`f'_c2 = string(r(N), "%9.0fc")
        di "`r`f'_c2'"
	
    * Add joint F-test for covariate balance
    reghdfe win_in_batch $vars_21 if inrange(batch, 7, 22) & batch_after_s21 ==1, absorb(c.stratum_win_prob#batch batch) $vce
    test $vars_21
    
    local fstr  = string(r(F), "%4.2f")
    di "`fstr'"
    scalar pval = r(p)
    local stars = cond(pval < 0.01, "***", cond(pval < 0.05, "**", cond(pval < 0.10, "*", "")))

    // ** write table header

    local tex_file = "$KP_output/tables/descriptive/tex/TableA6.tex"

    if `k' ==1 {
        tempname myfile
        #delimit ;
        file open `myfile' using "`tex_file'", write replace;
        file write `myfile'
        _n "\hline \hline"
        _n "Variable & Treatment & Control & Difference \\"
        _n "& \multicolumn{1}{c}{(1)} &\multicolumn{1}{c}{(2)} &\multicolumn{1}{c}{(3)} \\"
        _n "\hline" 
        ;
        file close `myfile' ;
        #delimit cr
    }
    else {
        tempname myfile
        #delimit ;
        file open `myfile' using "`tex_file'", write append;
        file write `myfile'
        _n "\begin{minipage}[t]{0.7\textwidth}"
        _n "\begin{threeparttable}"
        _n "\begin{tabular}{l*{3}{c}}"
        _n "\hline \hline"
        _n " &Treatment & Control & Difference \\"
        _n " & \multicolumn{1}{c}{(1)} &\multicolumn{1}{c}{(2)} &\multicolumn{1}{c}{(3)} \\"
        _n "\hline" 
        ;
        file close `myfile' ;
        #delimit cr
    }
    

    ** write table body

    di "`=`num'*2'"

    forval row = 1 / `=`num'*2' {
        tempname myfile
        #delimit ;
        file open `myfile' using "`tex_file'", write append;
        file write `myfile'
        _n "`r`row'_c0' & `r`row'_c1' & `r`row'_c2' & `r`row'_c3' \\" ;
        file close `myfile';
        #delimit cr
    }

    ** write table footer

    if `k' ==1 {
        tempname myfile
        #delimit ;
        file open `myfile' using "`tex_file'", write append;
        file write `myfile'
        _n "\end{tabular}"
        _n "\end{threeparttable}"
        _n "\end{minipage}%" 
        ;
        file close `myfile' ;
        #delimit cr
    }
    else {
        tempname myfile
        #delimit ;
        file open `myfile' using "`tex_file'", write append;
        file write `myfile'
	_n "\\ F-stat (joint test) &           &           &  `fstr'`stars' \\"
        _n "Observations & `r`f'_c1' & `r`f'_c2' & `r`f'_c3' \\"
        _n "Batches & 18-22 & 18-22 & 18-22 \\"
        ;
        file close `myfile';
        #delimit cr
    }
}
